package es

import (
	"gitee.com/mjun1833/buildnotification/config"
	"github.com/olivere/elastic/v7"
	"log"
	"net/http"
	"os"
	"sync"
	"time"
)

var once sync.Once
var instance *Client

type Client struct {
	*elastic.Client
	conf *Conf
}

func GetInstance() *Client {
	once.Do(func() {
		conf := &Conf{}
		err := config.GetInstance().UnmarshalKey("base.es", conf)
		if err != nil {
			panic(err)
		}

		var httpClient = &http.Client{
			Timeout: time.Second * time.Duration(conf.Timeout),
			Transport: &http.Transport{
				// Disable long-live connection
				//DisableKeepAlives: false,
				// This is to avoid the time_wait in connections
				//MaxIdleConnsPerHost: -1,
				// 增大连接池大小  防止 time_wait
				MaxIdleConns:        conf.MaxIdleConns,
				MaxIdleConnsPerHost: conf.MaxIdleConnsPerHost,
			},
		}

		var option []elastic.ClientOptionFunc

		option = append(option,
			elastic.SetURL(conf.Host...),
			elastic.SetHttpClient(httpClient),
			elastic.SetSniff(false),
			elastic.SetBasicAuth(conf.Username, conf.Password),
		)

		if conf.IsShowLog {
			option = append(option,
				elastic.SetErrorLog(log.New(os.Stderr, "ELASTIC ", log.LstdFlags)),
				elastic.SetInfoLog(log.New(os.Stdout, "", log.LstdFlags)),
			)
		}

		esClient, err := elastic.NewClient(option...)
		if err != nil {
			panic("create elasticsearch client failed, err: " + err.Error())
		}

		instance = &Client{
			Client: esClient,
			conf:   conf,
		}
	})

	return instance
}
